/*
 * @Author: huangyq
 * @Date: 2022-04-13 16:50:23
 * @LastEditTime: 2022-06-14 14:13:55
 * @LastEditors: huangyq
 * @Description: 获取请求实例
 * @FilePath: /vue3-boilerplate-pc-client/src/plugins/httpHelper/instance/index.ts
 */
import { AxiosInstance, AxiosRequestHeaders, AxiosRequestConfig } from 'axios'
import { createHttpInstance, IInstanceOpt } from './HttpInstance'

let httpRequest: AxiosInstance | null = null

const defaultToastFunction = (code: string, message: string) => {
  console.log(`错误提示[http-helper]: 错误码-${code}, 错误信息-${message}`)
  return Promise.resolve(message)
}
const defaultResponseTokenHandler = (code: string) => {
  code
}
const defaultRequestTokenHandler = (request: AxiosRequestConfig) => {
  request!.headers!.token = sessionStorage.getItem('token') || ''
}
const defaultRequestPermissionHandler = (request: AxiosRequestConfig) => {
  request
}

export default function createHttpRequest(options: {
  headers?: AxiosRequestHeaders
  toastFunction?: (code: string, message: string) => void
  responseTokenHandler?: (code: string) => void
  requestTokenHandler?: (request: AxiosRequestConfig) => void
  requestPermissionHandler?: (request: AxiosRequestConfig) => void
}) {
  const {
    headers,
    toastFunction,
    responseTokenHandler,
    requestTokenHandler,
    requestPermissionHandler
  } = options
  if (!httpRequest) {
    const options: IInstanceOpt = {
      baseURL: '/',
      headers: headers,
      toast: toastFunction || defaultToastFunction,
      responseTokenHandler: responseTokenHandler || defaultResponseTokenHandler,
      requestTokenHandler: requestTokenHandler || defaultRequestTokenHandler,
      requestPermissionHandler:
        requestPermissionHandler || defaultRequestPermissionHandler
    }
    httpRequest = createHttpInstance(options)
  }
  return httpRequest
}
